import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from django.db.models import Sum
from .models import ReadNum, ReadDetail


def read_statistics_once_read(request, obj):
    """
    不同模块 阅读数+1 方法
    :param request: 请求
    :param obj: 模块信息
    :return: cookie标志
    """
    ct = ContentType.objects.get_for_model(obj)
    key = "{0}_{1}_read".format(ct.model, obj.pk)

    if not request.COOKIES.get(key):
        # 总阅读数+1 get_or_create方法 没有查询到就创建
        read_num, created = ReadNum.objects.get_or_create(content_type=ct, object_id=obj.pk)
        read_num.read_num += 1
        read_num.save()

        # 当天的阅读数+1
        date = timezone.now().date()
        read_detail, created = ReadDetail.objects.get_or_create(content_type=ct, object_id=obj.pk, date=date)
        read_detail.read_num += 1
        read_detail.save()
    return key


def get_seven_days_read_data(content_type):
    """
    :param content_type: 模块类型
    :return:
    """
    today = timezone.now().date()
    read_nums = []
    dates = []
    for i in range(6, 0, -1):
        # timedelta 天数差值
        date = today - datetime.timedelta(days=i)
        dates.append(date.strftime('%m/%d'))
        read_details = ReadDetail.objects.filter(content_type=content_type, date=date)
        # aggregate 聚合
        result = read_details.aggregate(read_num_sum=Sum('read_num'))
        read_nums.append(result['read_num_sum'] or 0)

    return dates, read_nums


def get_today_hot_blog(context_type):
    """
    获取今天热门博客
    :param context_type:
    :return:
    """
    today = timezone.now().date()
    read_details = ReadDetail.objects.filter(content_type=context_type, date=today).order_by('-read_num')
    # 取前七条博客
    return read_details[:7]


def get_yesterday_hot_blog(context_type):
    """
    获取昨天热门博客
    :param context_type:
    :return:
    """
    today = timezone.now().date()
    yesterday = today - datetime.timedelta(days=1)
    read_details = ReadDetail.objects.filter(content_type=context_type, date=yesterday).order_by('-read_num')
    return read_details[:7]
